import {
  CallHandler,
  ExecutionContext,
  Injectable,
  NestInterceptor,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

export interface Response<T> {
  data: T;
}

@Injectable()
export class TransformInterceptor<T>
  implements NestInterceptor<T, Response<T>> {
  intercept(
    context: ExecutionContext,
    next: CallHandler<T>,
  ): Observable<Response<T>> {
    const ctx = context.switchToHttp();
    const response = ctx.getResponse();
    const request = ctx.getRequest();
    return next.handle().pipe(
      map((data: any) => ({
        // @ts-ignore
        pageSize: data?.pageSize ? data.pageSize : undefined,
        current: data?.current ? data.current : undefined,
        total: data?.total ? data.total : undefined,
        success: data?.success === false ? false : true,
        status: 200,
        timestamp: new Date().toISOString(),
        path: request.url,
        data: data?.data ? data.data : data,
        // @ts-ignore
        message: data?.message || '操作成功',
      })),
    );
  }
}
// status,
// timestamp: new Date().toISOString(),
// path: request.url,
// error,
// message,
